<?php
 
namespace app\admin\service;
use think\Model;
use app\admin\model\Member as MemberModel;

class Member extends Model
{
    public function login($username, $password)
    {
        $map['username'] = $username;
        /* 获取用户数据 */
        $info = MemberModel::get($map);
        if (empty($info) || !$info['state']) {
            return -1;
        }
        /* 验证用户密码 */
        $authKey = \think\Config::get('uc_auth_key');
        if(think_ucenter_md5($password, $authKey) === $info['password']){
            //记录行为
            action_log('user_login', 'member', $info['uid'], $info['uid']);
            $this->autoLogin($info);
            return $info['uid']; //登录成功，返回用户ID
        } else {
            return -2; //密码错误
        }
    }
    
    /**
     * 自动登录用户
     * @param  integer $user 用户信息数组
     */
    private function autoLogin($user){
        /* 更新登录信息 */
        $data = array(
            'uid'             => $user['uid'],
            'login'           => array('exp', '`login`+1'),
            'last_login_time' => time(),
            'last_login_ip'   => get_client_ip(1),
        );
        MemberModel::where(['uid'=>$user['uid']])->update($data);
        /* 记录登录SESSION和COOKIES */
        $auth = [
            'uid'             => $user['uid'],
            'username'        => $user['username'],
            'last_login_time' => $user['last_login_time'],
        ];
        
        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));
    }
    
    /**
     * 注销当前用户
     * @return void
     */
    public function logout(){
        session('user_auth', null);
        session('user_auth_sign', null);
    }
}